<?php

declare(strict_types=1);

namespace App\Controller\Home\User;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\Admin\Roles;
use App\Model\Cooperation;
use App\Model\Coupon;
use App\Model\CouponRecord;
use App\Model\Device;
use App\Model\Distributors;
use App\Model\MainBanner;
use App\Model\User;
use App\Model\White;
use App\Services\SmsService;
use Carbon\Carbon;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Util\JWTUtil;
use App\Services\Wechat;
use App\Controller\AbstractController;


class UserCouponController extends AbstractController
{
    use ResponseMsg;

    #[inject]
    protected User $user;

    #[inject]
    protected MainBanner $mainBanner;

    #[inject]
    protected Device $device;

    #[inject]
    protected CouponRecord $couponRecord;

    #[inject]
    protected Coupon $coupon;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
        $this->wechat = container()->get(Wechat::class);
    }


    /**新用户体验券发放
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function receive(RequestInterface $request):ResponseInterface{
        $info = $this->user->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $sn= $request->input('sn');
        $device = $this->device->where('sn',$sn)->first();
        if(!$device){
            return $this->error(1001,'设备编号不存在');
        }
        if($device->child_distributor_id){
            $distributorId = $device->child_distributor_id;
        }else{
            $distributorId = $device->distributor_id;
        }
        $today = date('Y-m-d',time());
        $coupons = $this->coupon->where('distributor_id',$distributorId)
         ->where('type',$this->coupon::TYPE_MAP[$this->coupon::TYPE_NEW_USER ])
         ->where('start_date','<=', $today)
         ->where('end_date','>=',$today)
         ->where('is_active',1)
         ->get()
         ->toArray();
        try{
            $nowCoupon =[];
            foreach($coupons as $k =>$v){
                $cacheKey = Coupon::COUPON_DEVICE_CACHE . $v['id'];
                $deviceMap = $this->redis->sMembers($cacheKey);
                if($deviceMap){
                    if(in_array($device->id,$deviceMap)){
                        $insertRecord = [];
                        $check = $this->couponRecord->where('coupon_id',$v['id'])
                            ->where('user_id',$info['id'])
                            ->count();
                        if(!$check){
                            $nowCoupon[] = $v;
                            for($i=0; $i<$v['quantity']; $i++){
                                $insertRecord[] = [
                                    'coupon_id'=>$v['id'],
                                    'user_id'=>$info['id'],
                                    'expires_at'=>date('Y-m-d H:i:s',time()+(60*60*24*$v['days'])),
                                    'device_id' =>$device->id,
                                    'station_id'=>$device->station_id,
                                    'created_at'=>date('Y-m-d H:i:s',time())
                                ];
                            }
                            CouponRecord::insert($insertRecord);
                        }
                    }
                }
            }
            return $this->success($nowCoupon);
        }catch (\Exception $e){
            return $this->error(1001,'操作繁忙 请稍后重试');
        }
    }

    /**添加白名单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function addWhite(RequestInterface $request):ResponseInterface{
        $info = $this->user->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $sn = $request->input('sn');
        $sn = trim($sn);
        $device = Device::where('sn',$sn)->first();
        if(!$device){
            return $this->error(code: 1001, msg: '设备编号不存在');
        }

        if($device->child_distributor_id){
            $save['distributor_id'] = $device->child_distributor_id;
        }else{
            $save['distributor_id'] = $device->distributor_id;
        }
        $save['device_id'] = $device->id;
        $save['user_id'] = $info['id'];
        $check = White::where('device_id',$save['device_id'])
            ->where('distributor_id',$save['distributor_id'])
            ->where('user_id',$info['id'])
            ->where('is_check','<>',White::ERROR)
            ->count();
        if($check){
            return $this->error(code: 1001, msg: '您已申请过白名单，请勿重复申请');
        }
        White::create($save);
        return $this->success();
    }

    /**检查用户是否为设备白名单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkWhite(RequestInterface $request):ResponseInterface{
        $sn = $request->input('sn');
        $sn = trim($sn);
        $info = $this->user->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $device = Device::where('sn', $sn)->first();
        $whiteKey ='WHITE_DEVICE_'. $device->id;
        $checkWhite = redis()->sMembers($whiteKey);
        $data['white'] =false;
        if($checkWhite){
            if(in_array($info['id'],$checkWhite)){
                $data['white'] = true;
            }
        }
        return $this->success($data);
    }



    /**获取我的设备优惠券列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selfList(RequestInterface $request):ResponseInterface{
        $sn = $request->input('sn');
        $sn = trim($sn);
        $info = $this->user->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $where['user_id'] = $info['id'];

        if($sn){
            $device = $this->device->where('sn',$sn)->first();
            if(!$device){
                return $this->error(1001,'设备编号sn不存在');
            }
            $where['device_id'] = $device->id;
        }

        $list = $this->couponRecord->where($where)
            ->get(['id','coupon_id','user_id','expires_at','used_at','device_id'])
            ->toArray();
        foreach($list as $k => $v){
            $list[$k]['coupon'] = $this->coupon->where('id',$v['coupon_id'])
                ->first(['id','type','fee']);
            $list[$k]['sn'] = $this->device->where('id',$v['device_id'])->value('sn');
            if($v['used_at']){
                $list[$k]['status'] = 'used';
            }else{
                $now = date('Y-m-d H:i:s',time());
                if($v['expires_at'] > $now){
                    $list[$k]['status'] = 'normal';
                }else{
                    $list[$k]['status'] = 'expires';
                }
            }
        }
        return $this->success($list);
    }


    /**获取满赠活动
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getMoneyCoupon(RequestInterface $request):ResponseInterface{
        $sn= $request->input('sn');
        $sn = trim($sn);
        $device = $this->device->where('sn',$sn)->first();

        if(!$device){
            return $this->error(1001,'设备编号不存在');
        }
        if($device->child_distributor_id){
            $distributorId = $device->child_distributor_id;
        }else{
            $distributorId = $device->distributor_id;
        }
        $today = date('Y-m-d',time());

        $coupons = $this->coupon->where('distributor_id',$distributorId)
            ->where('type',$this->coupon::TYPE_MAP[$this->coupon::TYPE_RECHARGE_RECEIVE])
            ->where('start_date','<=', $today)
            ->where('end_date','>=',$today)
            ->where('is_active',1)
            ->first();
        if(!$coupons){
            return $this->success();
        }
        $cacheDevice = Coupon::COUPON_DEVICE_CACHE . $coupons->id;
        $devices = redis()->sMembers($cacheDevice);
        if(!in_array($device->id,$devices)){
            return $this->success();
        }
        $cacheKey = Coupon::COUPON_MONEY_CACHE . $coupons->id;
        $coupons->moneys =  $this->redis->hGetAll($cacheKey);
        return $this->success($coupons);
    }

}
